package com.xscha.soyue.common.core.json.module;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.xscha.soyue.common.core.exception.status.SoyStatusCode;
import com.xscha.soyue.common.core.exception.status.StatusCode;
import com.xscha.soyue.common.core.json.BeanJsonModule;

import java.io.IOException;
import java.util.Objects;

/**
 * Title: DustStatusCodeModule
 *
 * @author Vondser
 * @version V2024.1.0
 */
public class SoyStatusCodeModule extends BeanJsonModule {

	private static final long serialVersionUID = -8007588611660914928L;

	@Override
	public void registerModels() {
		addSerializer(SoyStatusCode.class, new Serializer());
		addDeserializer(SoyStatusCode.class, new Deserializer());
	}

	static class Serializer extends JsonSerializer<SoyStatusCode> {

		@Override
		public Class<SoyStatusCode> handledType() {
			return SoyStatusCode.class;
		}

		@Override
		public void serialize(SoyStatusCode value, JsonGenerator gen, SerializerProvider serializers)
				throws IOException {
			if (Objects.nonNull(value)) {
				gen.writeStartObject();
				gen.writeNumberField("code", value.getCode());
				gen.writeStringField("message", value.getMessage());
				gen.writeEndObject();
				return;
			}
			gen.writeNull();
		}

	}

	static class Deserializer extends JsonDeserializer<SoyStatusCode> {

		@Override
		public SoyStatusCode deserialize(JsonParser p, DeserializationContext ctxt)
				throws IOException, JsonProcessingException {
			return p.readValueAs(StatusCode.class);
		}

	}

}
